package dy.spec.edu.week13_home02;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FirstActivity extends AppCompatActivity {
    private static final String TAG = "FristActivity";
    private SwipeRefreshLayout swipeRefreshLayout;
    List<Message> messageList = null;
    List<Message> mList = null;
    private int a=0;
    LoadMoreListView mListView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light);
        sendRequestWihtOkhttp();
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshWx();
            }
        });
        mListView =(LoadMoreListView)findViewById(R.id.imlv);
        mListView.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
            @Override
            public void onloadMore() {
                loadMore();
            }
        });
    }

    private void loadMore() {
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(a>=10) {
                            a -= 10;
                            sWihtOkhttp();
                            mListView.setLoadCompleted();
                        }else{
                            Toast.makeText(FirstActivity.this,"拉到最底部",Toast.LENGTH_SHORT).show();
                            mListView.setLoadCompleted();
                        }
                    }
                });
            }
        }.start();
    }

    private void sWihtOkhttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //构造客户端，相当于浏览器
                    OkHttpClient client = new OkHttpClient();
                    //构造请求，相当于在浏览器里输入地址
                    Request request = new Request
                            .Builder()
                            .url("http://www.yyjsx.xyz/api/message/find?messageCategory=WECHAT&limit=10&start="+a)
                            .build();
                    //发送请求，相当于在浏览器按回车
                    Response response = client.newCall(request).execute();
                    String body = response.body().string();
                    pJson(body);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void refreshWx(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(a<=messageList.size()) {
                            a += 10;
                            sendRequestWihtOkhttp();

                            swipeRefreshLayout.setRefreshing(false);
                        }else {
                            Toast.makeText(FirstActivity.this,"无最新消息",Toast.LENGTH_SHORT).show();
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    }
                });
            }
        }).start();
    }
    private void sendRequestWihtOkhttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //构造客户端，相当于浏览器
                    OkHttpClient client = new OkHttpClient();
                    //构造请求，相当于在浏览器里输入地址
                    Request request = new Request
                            .Builder()
                            .url("http://www.yyjsx.xyz/api/message/find?messageCategory=WECHAT&limit=10&start="+a)
                            .build();
                    //发送请求，相当于在浏览器按回车
                    Response response = client.newCall(request).execute();
                    String body = response.body().string();
                    parseJson(body);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void parseJson(String jsonStr){
        try {
            JSONObject jobj = new JSONObject(jsonStr);
            String dataStr = jobj.getString("data");
            Gson gson = new Gson();
            messageList = gson.fromJson(dataStr,new TypeToken<List<Message>>(){}.getType());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MessageAdapter fa = new MessageAdapter(FirstActivity.this, R.layout.message_item, messageList);
                    ListView lv = (ListView)findViewById(R.id.imlv);
                    lv.setAdapter(fa);
                    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Message message = messageList.get(position);
                            Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
                            intent.putExtra("title",message.getTitle());
                            intent.putExtra("preview",message.getPreview());
                            intent.putExtra("content",message.getSummary());
                            intent.putExtra("date",message.getCreateDate());
                            startActivity(intent);//启动Activity
                        }
                    });
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    private void pJson(String jsonStr){
        try {
            JSONObject jobj = new JSONObject(jsonStr);
            String dataStr = jobj.getString("data");
            Gson gson = new Gson();
            mList = gson.fromJson(dataStr,new TypeToken<List<Message>>(){}.getType());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    for(Message message :mList){
                        messageList.add(message);
                    }
                    MessageAdapter fa = new MessageAdapter(FirstActivity.this, R.layout.message_item, messageList);
                    ListView lv = (ListView)findViewById(R.id.imlv);
                    lv.setAdapter(fa);
                    fa.notifyDataSetChanged();
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}